package com.heima.comment.service.impl;

import com.heima.apis.user.UserFeign;
import com.heima.apis.wemedia.WemediaFeign;
import com.heima.comment.service.CommentRepayService;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.CommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private UserFeign userFeign;


    /**
     * 评论回复点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeCommentRepay(CommentRepayLikeDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApCommentRepay commentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);

        if (dto.getOperation() == 0) {
            //点赞
            commentRepay.setLikes(commentRepay.getLikes() + 1);
            mongoTemplate.save(commentRepay);
            //存入评论回复点赞表
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentId(dto.getCommentRepayId());
            apCommentRepayLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentRepayLike);
        } else {
            //取消点赞
            commentRepay.setLikes(commentRepay.getLikes() == 0 ? 0 : commentRepay.getLikes() - 1);
            mongoTemplate.save(commentRepay);
            //删除评论回复点赞表
            Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentRepayId()));
            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("likes", commentRepay.getLikes());
        return ResponseResult.okResult(map);
    }

    /**
     * 评论回复保存
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //字数限制
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能大于140个字");
        }
        //评论内容垃圾检查
        List<WmSensitive> wmSensitiveList = wemediaFeign.getAll();
        List<String> sensitiveList = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitiveList);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(dto.getContent());
        if (map.size() > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前评论中有违规内容" + map);
        }
        //保存评论回复
        ApUser apUser = userFeign.findById(user.getId());
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setLikes(0);
        //添加评论回复表
        mongoTemplate.insert(apCommentRepay);
        //评论表回复加一
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(apCommentRepay);
    }

    /**
     * 评论回复列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadRepay(CommentRepayDto dto) {
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.limit(10).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.okResult(apCommentRepays);
        }

        //获取所有评论回复的id
        List<String> idList = apCommentRepays.stream().map(apCommentRepay -> apCommentRepay.getId()).collect(Collectors.toList());
        //获取评论回复所有点赞的id
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").in(idList)), ApCommentRepayLike.class);

        List<CommentRepayVo> voList = new ArrayList<>();
        if (apCommentRepayLikes != null) {
            apCommentRepays.stream().forEach(apCommentRepay -> {
                CommentRepayVo vo = new CommentRepayVo();
                BeanUtils.copyProperties(apCommentRepay, vo);
                for (ApCommentRepayLike commentRepayLike : apCommentRepayLikes) {
                    if (apCommentRepay.getId().equals(commentRepayLike.getCommentId())) {
                        vo.setOperation(0);
                        break;
                    }
                }
                voList.add(vo);
            });
        } else {
            return ResponseResult.okResult(apCommentRepays);
        }
        return ResponseResult.okResult(voList);
    }
}
